package com.ymatou.shop.ui.activity.seller;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Date;

import com.ymatou.shop.R;
import com.ymatou.shop.account.Account;
import com.ymatou.shop.api.ApiRequest;
import com.ymatou.shop.api.ApiResponse;
import com.ymatou.shop.cache.ImageCache;
import com.ymatou.shop.cache.ImageUtil;
import com.ymatou.shop.cache.RequestInfo;
import com.ymatou.shop.cache.exception.CacheException;
import com.ymatou.shop.model.LoginResult;
import com.ymatou.shop.model.ResponseMessage;
import com.ymatou.shop.ui.activity.BaseHeaderActivity;
import com.ymatou.shop.ui.activity.LoginActivity;
import com.ymatou.shop.util.DateUtil;
import com.ymatou.shop.util.DeviceUtil;
import com.ymatou.shop.util.GlobalUtil;
import com.ymatou.shop.util.LogUtil;
import com.ymatou.shop.util.StringUtil;

import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView.ScaleType;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SlidingDrawer;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.ToggleButton;

public class AddProductActivity extends BaseHeaderActivity implements OnClickListener {

	private static final int REQUEST_ID_ADD_PRODUCT = 1;

	public final static String BITMAPS_KEY = "bitmpas";

	private EditText productDescriptionEditText, productPriceEditText, productStockEditText;
	private ToggleButton taxToggleButton;
	private Button submitButton;
	private String des, price, stock, lefttime;
	private View completeLayout;
	private LinearLayout mImageLayoutRoot;
	private ArrayList<Bitmap> mBitmaps;
	private boolean isTax;
	private int mLefttime = 8;
	private int mLayoutWidth;
	private int mImageSpace = 5;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_product_activity);

		getIntentData();
		setupViews();

		setupImageData();
	}

	public void getIntentData() {
		if (getIntent() != null) {
			mBitmaps = (ArrayList<Bitmap>) getIntent().getSerializableExtra(BITMAPS_KEY);
		}
		LogUtil.systemErr("" + mBitmaps);
	}

	private void setViewsCompleteProduct() {
		completeLayout = findViewById(R.id.layout);
		findViewById(R.id.textview1).setOnClickListener(this);
		findViewById(R.id.textview2).setOnClickListener(this);
	}

	@Override
	protected void setupViews() {
		super.setupViews();

		getTitleLeftImageButton().setImageResource(R.drawable.back_icon);
		getTitleLeftImageButton().setVisibility(View.VISIBLE);
		getTitleLeftImageButton().setBackgroundDrawable(null);

		productDescriptionEditText = (EditText) findViewById(R.id.product_description);
		productPriceEditText = (EditText) findViewById(R.id.product_price);
		productStockEditText = (EditText) findViewById(R.id.product_stock);

		mImageLayoutRoot = (LinearLayout)findViewById(R.id.image_root);
		
		taxToggleButton = (ToggleButton) findViewById(R.id.tax);
		taxToggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				isTax = isChecked;
			}
		});

		//	卖家测试账户EnjoyHealth 
		//	买家测试账户lunchzhao

		submitButton = (Button) findViewById(R.id.submit);
		submitButton.setOnClickListener(this);

		setViewsCompleteProduct();
		
		
	  final Spinner s1 = (Spinner) findViewById(R.id.spinner1);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
            this, R.array.product_lefttime, android.R.layout.simple_spinner_item);
//    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    s1.setAdapter(adapter);
    s1.setOnItemSelectedListener(
            new OnItemSelectedListener() {
                public void onItemSelected(
                        AdapterView<?> parent, View view, int position, long id) {
//                    GlobalUtil.shortToast(AddProductActivity.this, "Spinner1: position=" + position + " id=" + id);
                    TextView mTextView = (TextView)view;
                    mTextView.setTextColor(getResources().getColor(R.color.text_red));
                    mTextView.setText(position > 0 ? "0" + position + ":00:00" : "30:00");
          					mLefttime = position;
                }

                public void onNothingSelected(AdapterView<?> parent) {
//                	GlobalUtil.shortToast(AddProductActivity.this, "Spinner1: unselected");
                }
            });
	}

	private void uploadPic(ArrayList<Bitmap> bitmaps) {
		//		for (int i=0;i<bitmaps.size();i++){
		//			uploadPic(bitmaps.get(i));
		//		}
		loadPic(bitmaps);
	}

	private AsyncTask<ArrayList<Bitmap>, Void, String> uploadPicTask;
	private String uploadPics;
	ResponseMessage mResponseMessage;
	private void loadPic(ArrayList<Bitmap> bitmaps) {
		final StringBuffer mStringBuffer = new StringBuffer();
		uploadPicTask = new AsyncTask<ArrayList<Bitmap>, Void, String>() {

			@Override
			protected String doInBackground(ArrayList<Bitmap>... params) {
				if (params != null && params.length > 0) {
					mStringBuffer.append("[");
					for (int i = 0; i < params[0].size(); i++) {
						ByteArrayOutputStream baos = new ByteArrayOutputStream();
						params[0].get(i).compress(Bitmap.CompressFormat.JPEG, 100, baos);
						try {
							String response = ImageUtil.uploadImageFile(AddProductActivity.this, "123.jpg", "image/jpeg", baos.toByteArray());
							mResponseMessage = ApiResponse.getUploadImageUrl(response);
							if (mResponseMessage.status == 200 && StringUtil.isNotEmpty(mResponseMessage.picUrl)) {
								if (i > 0) {
									mStringBuffer.append(",");
								}
								mStringBuffer.append(mResponseMessage.picUrl);
							} else {
//								GlobalUtil.shortToast(AddProductActivity.this, mResponseMessage.message);
								return null;
							}
						} catch (CacheException e) {
							e.printStackTrace();
							return null;
						}
					}
					mStringBuffer.append("]");
					uploadPics = mStringBuffer.toString();
					
				}

				return uploadPics;
			}

			@Override
			protected void onPostExecute(String result) {
				if (uploadPics != null && uploadPics.length() > 0){
					RequestInfo request = ApiRequest.addProduct("position", uploadPics, des, stock, price, mLefttime > 0 ? DateUtil.format(DateUtil.addHours(new Date(), mLefttime), "yyyy-MM-dd HH:mm:ss") : DateUtil.format(DateUtil.addMinutes(new Date(), 30), "yyyy-MM-dd HH:mm:ss"), isTax ? 0 : 1);
					getCacheManager().register(REQUEST_ID_ADD_PRODUCT, request, AddProductActivity.this);	
				}else {
					GlobalUtil.shortToast(AddProductActivity.this, "图片上传失败 " + mResponseMessage.message);
				}
				
				super.onPostExecute(result);
			}

			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
			}
		};

		uploadPicTask.execute(bitmaps);
	}

	@Override
	public void onCacheSuccess(int requestId, RequestInfo requestInfo, Object response) {
		cancelProgressDialog();
		switch (requestId) {
		case REQUEST_ID_ADD_PRODUCT:
			ResponseMessage mResponseMessage = ApiResponse.addProduct((String) response);
			if (mResponseMessage.isSuccess()) {
				completeLayout.setVisibility(View.VISIBLE);
				findViewById(R.id.layout2).setVisibility(View.GONE);
				submitButton.setVisibility(View.GONE);
				getTitleLeftImageButton().setVisibility(View.GONE);
			}
			break;

		default:
			super.onCacheSuccess(requestId, requestInfo, response);
			break;
		}
		
	}

	@Override
	public void onCacheFailed(int requestId, RequestInfo requestInfo, CacheException error) {
		switch (requestId) {
		case REQUEST_ID_ADD_PRODUCT:
			ResponseMessage mResponseMessage = ApiResponse.addProduct((String) error.getOrgResponse());			
			GlobalUtil.shortToast(this, mResponseMessage.message);
			break;

		default:
			super.onCacheFailed(requestId, requestInfo, error);
			break;
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.submit:
			des = productDescriptionEditText.getText().toString();
			if (StringUtil.isEmpty(des)) {
				GlobalUtil.shortToast(v.getContext(), R.string.des_not_null);
				productDescriptionEditText.requestFocus();
				return;
			}
			price = productPriceEditText.getText().toString();
			if (StringUtil.isEmpty(price) || price.equals("0")) {
				GlobalUtil.shortToast(v.getContext(), R.string.price_not_zero);
				productPriceEditText.requestFocus();
				return;
			}
			stock = productStockEditText.getText().toString();
			if (StringUtil.isEmpty(stock) || stock.equals("0")) {
				stock = "0";
				//				GlobalUtil.shortToast(v.getContext(), resId);
			}
			setMeesage(R.string.upload_ing_text);
			showProgressDialog();
			uploadPic(mBitmaps);
			break;
		case R.id.textview1:
			//进入已发布商品列表
			break;
		case R.id.textview2:
			//发布新活动
			
			break;
		case R.id.title_left_image_button:
			onBackPressed();
			break;
		default:
			break;
		}
	}

	
	private void setupImageData() {
		if (mBitmaps == null || mBitmaps.size() == 0) {
			return;
		}
		int space = getResources().getDimensionPixelOffset(R.dimen.add_product_image_space);
		mImageSpace = space;
		Rect rect = DeviceUtil.getScreenRect(this);
		mLayoutWidth = rect.width() - space * 2;
		
		
		mImageLayoutRoot.removeAllViews();
		
		if (mBitmaps.size() > 3) {
			setupImageSixData();
		} else if (mBitmaps.size() == 2) {
			setupImageTwoData();
		}else if (mBitmaps.size() > 2) {
			setupImageThreeData();
		} 
		
		else {
			setupImageOneData();
		}
	}
	
	private void setupImageSixData() {
		mImageLayoutRoot.setOrientation(LinearLayout.VERTICAL);
		
		int width = (mLayoutWidth - mImageSpace * 4)  / 3;
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, width);
		
		for (int i = 0; i < 2; i++) {
			LinearLayout layout = new LinearLayout(this);
			layout.setOrientation(LinearLayout.HORIZONTAL);
			
			ImageView imageView = createImageView();
			setImageDrawable(imageView, mBitmaps.get(i * 3 + 0));
			params.setMargins(0, 0, mImageSpace, 0);
			layout.addView(imageView, params);
			
			if (i > 0){
				if (mBitmaps.size() > 4){
					imageView = createImageView();
					setImageDrawable(imageView, mBitmaps.get(i * 3 + 1));
					params.setMargins(mImageSpace, 0, mImageSpace, 0);
					layout.addView(imageView, params);		
				}	
			}else {
				imageView = createImageView();
				setImageDrawable(imageView, mBitmaps.get(i * 3 + 1));
				params.setMargins(mImageSpace, 0, mImageSpace, 0);
				layout.addView(imageView, params);	
			}
			
			if (i > 0){
				if (mBitmaps.size() > 5){
					imageView = createImageView();
					setImageDrawable(imageView, mBitmaps.get(i * 3 + 2));
					params.setMargins(0, 0, mImageSpace, 0);
					layout.addView(imageView, params);	
				}	
			}else {
				imageView = createImageView();
				setImageDrawable(imageView, mBitmaps.get(i * 3 + 2));
				params.setMargins(0, 0, mImageSpace, 0);
				layout.addView(imageView, params);
			}
			
			
			
			
			LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
			if (i == 0) {
				layoutParams.setMargins(0, 0, 0, mImageSpace);
			} else {
				layoutParams.setMargins(0, mImageSpace, 0, 0);
			}
			mImageLayoutRoot.addView(layout, layoutParams);
		}
	}
	
	private void setupImageThreeData() {
		mImageLayoutRoot.setOrientation(LinearLayout.HORIZONTAL);
		
		int width = (mLayoutWidth - mImageSpace * 4) / 3;
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, width);
		
		ImageView imageView = createImageView();
		setImageDrawable(imageView, mBitmaps.get(0));
		params.setMargins(0, 0, mImageSpace, 0);
		mImageLayoutRoot.addView(imageView, params);
		
		imageView = createImageView();
		setImageDrawable(imageView, mBitmaps.get(1));
		params.setMargins(mImageSpace, 0, mImageSpace, 0);
		mImageLayoutRoot.addView(imageView, params);
		
		imageView = createImageView();
		setImageDrawable(imageView, mBitmaps.get(2));
		params.setMargins(0, 0, mImageSpace, 0);
		mImageLayoutRoot.addView(imageView, params);
	}
	
	private void setupImageTwoData() {
		mImageLayoutRoot.setOrientation(LinearLayout.HORIZONTAL);
		
		int width = (mLayoutWidth - mImageSpace * 3) / 2;
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, width);
		
		ImageView imageView = createImageView();
		setImageDrawable(imageView, mBitmaps.get(0));
		params.setMargins(mImageSpace, 0, mImageSpace, 0);
		mImageLayoutRoot.addView(imageView, params);
		
		
		imageView = createImageView();
		setImageDrawable(imageView, mBitmaps.get(1));
		params.setMargins(0, 0, mImageSpace, 0);
		mImageLayoutRoot.addView(imageView, params);
	}
	
	private void setupImageOneData() {
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(mLayoutWidth, mLayoutWidth);
		ImageView imageView = createImageView();
		setImageDrawable(imageView, mBitmaps.get(0));
		mImageLayoutRoot.addView(imageView, params);
	}
	
	private void setImageDrawable(ImageView imageView, Bitmap bm) {
			imageView.setImageBitmap(bm);
	}
	
	private ImageView createImageView() {
		ImageView imageView = new ImageView(this);
		imageView.setScaleType(ScaleType.CENTER_CROP);
		return imageView;
	}
}
